package com.bnlr.lrparking.appui.order;


import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.ToastUtils;
import com.bnlr.lrparking.constant.LrConstant;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.bnlr.lrparking.app.Application;
import com.bnlr.lrparking.R;
import com.bnlr.lrparking.appui.order.stages.ByStagesDetailsActivity;
import com.bnlr.lrparking.appui.login.VerificaActivity;
import com.bnlr.lrparking.base.BaseFragment;
import com.bnlr.lrparking.app.AppConfig;
import com.bnlr.lrparking.model.BaseArrayBean;
import com.bnlr.lrparking.appui.order.adapter.OrderAdapter;
import com.bnlr.lrparking.appui.order.mode.OrderBean;
import com.bnlr.lrparking.appui.order.mode.OrderIntentBean;
import com.bnlr.lrparking.constant.Urls;
import com.bnlr.lrparking.view.CarCommon;
import com.bnlr.lrparking.widget.refresh.RefreshHolderUtil;
import com.bnlr.lrparking.widget.refresh.XRefreshLayout;
import com.bnlr.nohttp.CallServer;
import com.bnlr.nohttp.CustomHttpListener;
import com.yolanda.nohttp.NoHttp;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * 订单fragment
 * @author tian
 */
public class OrderFragment extends BaseFragment {
    private OrderAdapter adapter;
    private Unbinder unbinder;
    @BindView(R.id.order_refresh)
    XRefreshLayout xRefreshLayout;
    @BindView(R.id.order_rv)
    RecyclerView recyclerView;
    @BindView(R.id.ll_hint)
    LinearLayout empty;
    @BindView(R.id.tv_hint_tips)
    TextView tvEmpty;
    @BindView(R.id.iv_hint)
    ImageView ivEmpty;
    private List<OrderBean.DataBean> dataList = new ArrayList<>();
    private static final String ORDER_TAG = "order_tag";
    private int positionIndex;
    private int currentPage = 1;
    private int statusIndex;
    private OrderIntentBean orderIntentBean = new OrderIntentBean();
    public static OrderFragment newInstance(int position) {
        Bundle args = new Bundle();
        OrderFragment fragment = new OrderFragment();
        args.putInt(ORDER_TAG,position);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_order, container, false);
        unbinder = ButterKnife.bind(this,view);
        tvEmpty.setText("暂无订单记录哟~");
        ivEmpty.setImageResource(R.mipmap.norecord);
        positionIndex = getArguments().getInt(ORDER_TAG);
        switch (positionIndex) {
            case 0:
                // 全部
                statusIndex = 8;
                break;
            case 1:
                statusIndex = 0;
                break;
            case 2:
                statusIndex = 1;
                break;
            default:
                break;
        }
        initView();
        return view;
    }

    private void initView() {
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        xRefreshLayout.setRefreshViewHolder(RefreshHolderUtil.getRefreshHolder(getActivity()));
        xRefreshLayout.setDelegate(new XRefreshLayout.BGARefreshLayoutDelegate() {
            @Override
            public void onBGARefreshLayoutBeginRefreshing(XRefreshLayout refreshLayout) {
                currentPage = 1;
                getOrderList(currentPage);
            }
            @Override
            public boolean onBGARefreshLayoutBeginLoadingMore(XRefreshLayout refreshLayout) {
                return false;
            }
        });
        adapter = new OrderAdapter(dataList);
        recyclerView.setAdapter(adapter);
        adapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                currentPage = currentPage + 1;
                getOrderList(currentPage);
            }
        },recyclerView);

        adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                startActivity(new Intent(getActivity(),OrderDetailActivity.class)
                .putExtra("order_detail_id",dataList.get(position).getOrderNumber()));
            }
        });
        adapter.setOrderHandlerListener(new OrderAdapter.OrderHandlerListener() {
            @Override
            public void onDelete(View view, final int position, final OrderBean.DataBean item) {
                CarCommon carCommon = new CarCommon();
                carCommon.setClickSureListener(new CarCommon.ClickSureListener() {
                    @Override
                    public void setSure() {
                        deleteOrder(position,item.getId());
                    }
                });
                carCommon.CommonDialog(getActivity(),"确定要删除该订单吗",null);
            }

            @Override
            public void onPay(View view, OrderBean.DataBean item) {
                orderIntentBean.setId(item.getId()+"");
                orderIntentBean.setDealPrice(item.getDealPrice());
                orderIntentBean.setParkingId(item.getParkingId());
                orderIntentBean.setAdvanceMoney(item.getAdvanceMoney());
                orderIntentBean.setDealUserName(item.getDealUserName());
                orderIntentBean.setDealPhone(item.getDealPhone());
                orderIntentBean.setType(item.getPayType());
                startActivity(new Intent(getActivity(),OrderRetentionMoneyActivity.class)
                        .putExtra("order_bean",orderIntentBean));
            }
            @Override
            public void onStages(View view, OrderBean.DataBean item) {
                if (item.getIsByStage() == 0) {
                    if (item.getDealPrice() != 0) {
                        orderIntentBean.setId(item.getId()+"");
                        orderIntentBean.setDealPrice(item.getDealPrice());
                        orderIntentBean.setParkingId(item.getParkingId());
                        orderIntentBean.setAdvanceMoney(item.getAdvanceMoney());
                        orderIntentBean.setDealUserName(item.getDealUserName());
                        orderIntentBean.setDealPhone(item.getDealPhone());
                        orderIntentBean.setStatusInt(item.getStatusInt());
                        startActivity(new Intent(getActivity(), ByStagesDetailsActivity.class)
                                .putExtra("enter_stages_from", 2).putExtra("order_mode",orderIntentBean));
                    } else {
                        ToastUtils.showShort("此车位不支持分期");
                    }
                } else {
                    //分期过
                    orderIntentBean.setId(item.getId()+"");
                    orderIntentBean.setDealPrice(item.getDealPrice());
                    orderIntentBean.setParkingId(item.getParkingId());
                    startActivity(new Intent(getActivity(),StagesStepActivity.class)
                            .putExtra("order_mode",orderIntentBean));
                }
            }
        });

    }

    /**
     * 删除订单
     * @param position
     * @param id
     */
    private void deleteOrder(final int position, int id) {
        try {
            mRequest = NoHttp.createStringRequest(Urls.ORDER, LrConstant.POST);
            mRequest.add("action", "SetOrderStatus");
            mRequest.add("uid", AppConfig.getInstance().getString("uid", ""));
            mRequest.add("phonePara", Application.DEVICE_ID);
            mRequest.add("orderId", id);
            mRequest.add("status",4);
            // 添加到请求队列+
            CallServer.getRequestInstance().add(getActivity(), mRequest,
                    new CustomHttpListener<BaseArrayBean>(getActivity(), true, BaseArrayBean.class) {
                        @Override
                        public void doWork(BaseArrayBean data, String code) {
                            if (TextUtils.equals("1", code)) {
                                dataList.remove(position);
                                adapter.setNewData(dataList);
                                ToastUtils.showShort("订单删除成功");
                                if (dataList.size() == 0) {
                                    empty.setVisibility(View.VISIBLE);
                                }
                            } else {
                                ToastUtils.showShort(data.getMsg()+"");
                            }
                        }
                        @Override
                        public void onFinally(JSONObject obj, String code, boolean isSucceed) {

                        }
                    }, true);
        } catch (Exception e) {
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        currentPage = 1;
        getOrderList(currentPage);
    }


    /**
     * 获取订单列表
     * @param currentPage
     */
    private void getOrderList(final int currentPage) {
        try {
            mRequest = NoHttp.createStringRequest(Urls.ORDER, LrConstant.POST);
            mRequest.add("action", "GetUserOrderList");
            mRequest.add("uid", AppConfig.getInstance().getString("uid", ""));
            mRequest.add("phonePara", Application.DEVICE_ID);
            mRequest.add("pageIndex", currentPage);
            mRequest.add("status",statusIndex);
            // 添加到请求队列+
            CallServer.getRequestInstance().add(getActivity(), mRequest,
                    new CustomHttpListener<OrderBean>(getActivity(), true, OrderBean.class) {
                        @Override
                        public void doWork(OrderBean data, String code) {
                            if (TextUtils.equals("1", code)) {
                                if (adapter != null) {
                                    if (data != null && data.getData().size() != 0) {
                                        empty.setVisibility(View.GONE);
                                        if (currentPage == 1) {
                                            dataList.clear();
                                            dataList.addAll(data.getData());
                                            adapter.notifyDataSetChanged();
                                        } else {
                                            dataList.addAll(data.getData());
                                            adapter.notifyDataSetChanged();
                                        }
                                        adapter.loadMoreComplete();
                                    } else {
                                        if (currentPage == 1) {
                                            dataList.clear();
                                            adapter.notifyDataSetChanged();
                                            empty.setVisibility(View.VISIBLE);
                                        } else {
                                            adapter.loadMoreEnd();
                                        }
                                    }
                                }
                            } else {
                                ToastUtils.showShort(data.getMsg()+"");
                            }
                        }
                        @Override
                        public void onFinally(JSONObject obj, String code, boolean isSucceed) {
                            if (xRefreshLayout != null) {
                                xRefreshLayout.endRefreshing();
                            }
                            try {
                                if (!TextUtils.equals("1", code) && (obj.getString("msg").contains("用户已在其他手机上登录")||
                                        obj.getString("msg").contains("请重新登录") && positionIndex == 0)) {
                                    final CarCommon carCommon = new CarCommon();
                                    carCommon.setClickSureListener(new CarCommon.ClickSureListener() {
                                        @Override
                                        public void setSure() {
                                            Intent intent = new Intent(getActivity(), VerificaActivity.class);
                                            getActivity().startActivity(intent);
                                        }
                                    });
                                    carCommon.ReminderDialog(getActivity(), "登录信息已过期，是否重新登录？","下线通知","立即登录");
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    }, false);
        } catch (Exception e) {
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }
}
